<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>心理测评</el-breadcrumb-item>
		<el-breadcrumb-item>测评题库管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0">
		<el-form-item label="题目">
			<el-input v-model="queryInfo.title" placeholder="请选择题目名称" clearable @clear="query" />
		</el-form-item>
		<el-form-item label="测评名称">
			<el-input v-model="testName" placeholder="请选择测评名称" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="query">搜索</el-button>
			<el-button type="primary" @click="add">新增题目</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 数据表格 -->
	<el-table ref="multipleTableRef" :data="dataList" style="width: 100%" @selection-change="handleSelectionChange"
		border>
		<el-table-column type="selection" width="50" />
		<el-table-column property="id" label="ID" width="55" />
		<el-table-column property="title" label="题目" />
		<el-table-column property="psycTest.name" label="测评名称" />
		<el-table-column label="选项">
			<el-table-column v-for="index in 4" :key="index" :label="String.fromCharCode(65 + index - 1)" width="120">
				<template #default="scope">
					<span v-if="scope.row.options && scope.row.options.length > index - 1">
						{{ scope.row.options[index - 1].content }}
					</span>
					<span v-else>-</span>
				</template>
			</el-table-column>
		</el-table-column>
		<el-table-column fixed="right" label="操作" width="180">
			<template #default="scope">
				<el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
				<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[50, 60,70,80]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<!-- 新增和修改对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="600" @close="cancle">
		<el-form :model="topicData" label-width="100">
			<el-form-item label="题目">
				<el-input v-model="topicData.title" autocomplete="off" placeholder="请输入测评名称"></el-input>
			</el-form-item>
			<el-form-item label="测评id">
				<el-input v-model="topicData.psycTest.id" placeholder="请输入测评id"></el-input>
			</el-form-item>
			<el-form-item label="选项">
				<div style="width:100%">
					<div v-for="(option, idx) in topicData.options" :key="idx"
						style="display:flex;align-items:center;margin-bottom:8px;">
						<el-input v-model="option.content" :placeholder="`选项${String.fromCharCode(65+idx)}`"
							style="flex:1" />
						<el-button icon="el-icon-minus" type="danger" size="small" style="margin-left:8px"
							@click="removeOption(idx)" :disabled="topicData.options.length<=2"></el-button>
					</div>
					<el-button icon="el-icon-plus" type="primary" size="small" @click="addOption">添加选项</el-button>
				</div>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		getCurrentInstance,
		reactive
	} from 'vue'
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	const axios = getCurrentInstance().appContext.config.globalProperties.axios

	const total = ref(0)
	const testName = ref('')
	const queryInfo = ref({
		title: '',
		pageNum: 1,
		pageSize: 50,
	})
	const dataList = ref([])

	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map((item) => {
			return item.id
		})
		console.log(multipleSelection.value)
	}

	//组件加载完毕，查询数据
	onMounted(() => {
		query();
	});

	//查询数据的函数
	const query = () => {
		axios
			.get(`topic/pages?psycTest.name=${testName.value}`, {
				params: queryInfo.value,
			})
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list
					total.value = resp.data.total //pagehelper插件问题没解决，所以不准
				} else {
					ElMessage.error('查询数据失败')
				}
			})
	}


	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = 50 //pagehelper插件问题没解决，所以不准
		query()
	}

	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val
		query()
	}

	const title = ref('新增测评')
	const dialogFormVisible = ref(false)

	// 状态管理
	const topicData = ref({
		title: '',
		id: '',
		psycTest: {
			id: '',
			name: '' // 确保嵌套对象结构完整
		},
		options: [{
				content: ''
			},
			{
				content: ''
			}
		]
	});

	// 表单验证
	const validateForm = () => {
		if (!topicData.value.title.trim()) {
			ElMessage.error('题目不能为空');
			return false;
		}
		if (topicData.value.options.some(opt => !opt.content.trim())) {
			ElMessage.error('所有选项不能为空');
			return false;
		}
		return true;
	};

	// 取消操作
	const cancel = () => {
		resetForm();
		dialogFormVisible.value = false;
	};

	// 重置表单
	const resetForm = () => {
		topicData.value = {
			title: '',
			id: '',
			psycTest: {
				id: '',
				name: ''
			},
			options: [{
					content: ''
				},
				{
					content: ''
				}
			]
		};
	};

	// 新增/编辑提交
	const confirm = async () => {
		if (!validateForm()) return;

		try {
			let topicResp;
			let topicId; // 声明topicId变量

			// 判断是新增还是编辑
			if (topicData.value.id) {
				// 编辑操作：使用已有ID
				topicResp = await axios.put(`topic`, {
					id: topicData.value.id,
					title: topicData.value.title,
					testId: topicData.value.psycTest.id
				});
				topicId = topicData.value.id; // 使用前端已有ID
			} else {
				// 新增操作：获取后端返回的ID
				topicResp = await axios.post('topic', {
					title: topicData.value.title,
					testId: topicData.value.psycTest.id
				});
				console.log("topicResp",topicResp);
				topicId = topicResp.data.id; // ✅ 从后端响应中获取ID
				console.log('新增成功，题目ID:', topicId);
			}

			if (topicResp.code !== 200) {
				ElMessage.error('操作题目失败');
				return;
			}

			// 处理选项（先删除旧选项，再添加新选项）
			if (topicData.value.id) { // 编辑时才删除旧选项（新增时无旧选项）
				await axios.delete(`psycTestOption/byTopic/${topicId}`);
			}

			// 批量添加新选项
			const options = topicData.value.options
				.filter(opt => opt.content.trim())
				.map(opt => ({
					testTitleId: topicId,
					content: opt.content
				}));

			const optionResp = await axios.post('psycTestOption/batch', options);

			if (optionResp.code === 200) {
				ElMessage.success(topicData.value.id ? '编辑成功' : '新增成功');
				query();
				dialogFormVisible.value = false;
			} else {
				ElMessage.error('操作选项失败');
			}
		} catch (e) {
			console.error(e);
			ElMessage.error('请求失败');
		}
	};

	// 新增操作
	const add = () => {
		title.value = '新增题目';
		dialogFormVisible.value = true;
		resetForm(); // 使用统一的重置方法
	};

	// 编辑操作
	const edit = (row) => {
		title.value = '编辑题目';
		dialogFormVisible.value = true;

		// 确保数据结构一致
		topicData.value = {
			id: row.id || '',
			title: row.title || '',
			psycTest: {
				id: row.psycTest?.id || '',
				name: row.psycTest?.name || ''
			},
			options: row.options?.map(opt => ({
				content: opt.content || ''
			})) || [{
					content: ''
				},
				{
					content: ''
				}
			]
		};
	};





	//删除
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', 'Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				axios.delete(`topic/${id}?t=${new Date().getTime()}`).then((resp) => {
					if (resp.code == 200) {
						ElMessage.success('删除成功')

					} else {
						ElMessage.error('删除失败')
					}
					query()
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	//批量删除
	const batchRemove = () => {
		ElMessageBox.confirm('此操作将永久删除这些文件, 是否继续?', 'Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				axios
					.delete('topic', {
						params: {
							ids: multipleSelection.value.join(','),
						},
					})
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						query()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	const addOption = () => {
		topicData.value.options.push({
			text: ''
		})
	}
	const removeOption = (idx) => {
		if (topicData.value.options.length > 2) {
			topicData.value.options.splice(idx, 1)
		}
	}


	/* //点击新增测评按钮的时候，弹出对话框
	const add = () => {
	  dialogFormVisible.value = true
	}

	//编辑
	const edit = (row) => {
	  title.value = '编辑测评'
	  dialogFormVisible.value = true
	  evaluationData.value = row
	} */
</script>

<style>
	.el-breadcrumb {
		font-size: 14px;
		border-bottom: 1px solid #eee;
		padding-bottom: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-pagination {
		margin-top: 15px;
	}
</style>